# main.py
import logging
from logging.config import fileConfig

from fastapi import FastAPI,Request
from contextlib import asynccontextmanager
import uvicorn

from services.vector_store import VectorStoreService

from services.qa_service import initialize_rag_chain
from routers.qa import router as qa_router
from routers.rag import router as rag_router

fileConfig("logging.conf")
# 获取日志记录器
logger = logging.getLogger("app")



@asynccontextmanager
async def lifespan(app: FastAPI):
    try:
        logger.info("lifespan...")
        # 初始化向量服务
        vector_service = VectorStoreService()
        app.state.vector_service = vector_service
        logger.info("向量服务初始化成功")

        # 检查向量存储是否已加载
        if not vector_service.vector_store:
            logger.warning("向量存储未加载，请先运行 ingest.py")

    except Exception as e:
        logger.error(f"启动时初始化失败: {str(e)}")
        app.state.vector_service = None  # 设置为None避免后续错误

    yield

    # 清理资源（可选）
    logger.info("应用正在关闭")
app = FastAPI(title="RAG API",lifespan=lifespan)
app.include_router(rag_router, prefix="/api/v1")
# 注册路由
app.include_router(qa_router)
@app.get("/health")
async def health_check(request: Request):
    status = {
        "status": "ok",
        "vector_service_initialized": hasattr(request.app.state, "vector_service") and request.app.state.vector_service is not None
    }
    return status


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=1602, reload=False)
